/**
* @description  : 面单地图
* @descriptionDetail :
* @copyright    :
* @create       : 2024/8/15
*/

<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="retailBack" style="z-index: 99999"></theme-navbar>
    <!-- #endif -->

    <view class="content" style="width: 100%">
      <!-- 地图展示 -->
      <view :style="{width: getContainerWidth(), height: getContainerHeight()}" id="container"></view>
    </view>
    <u-popup :maskCloseAble="false" mode="bottom" height="60%" v-model="partySelectShow" z-index="990">
      <u-icon style="position: absolute;right: 5px;top: 5px;" size="48" name="close-circle-fill" color="#c0c4cc"  @click="partySelectShow = false"/>
      <u-form style="padding: 40rpx;margin-top: 30rpx" :model="formData" ref="uForm">
        <u-form-item :label-width="labelWidth" label="面单编号" prop="orgUuid" label-position="left" >
          <u-input
              placeholder=""
              :disabled="true"
              :custom-style="pointerStyle"
              v-model="formData.billCode"
          >
          </u-input>
        </u-form-item>
        <u-form-item :label-width="labelWidth" label="快递公司名称" prop="orgUuid" label-position="left" >
          <u-input
              placeholder=""
              :disabled="true"
              :custom-style="pointerStyle"
              v-model="formData.expressName"
          >
          </u-input>
        </u-form-item>
        <u-form-item :label-width="labelWidth" label="包裹数量" prop="orgUuid" label-position="left" >
          <u-input
              placeholder=""
              :disabled="true"
              :custom-style="pointerStyle"
              v-model="formData.packageNum"
          >
          </u-input>
        </u-form-item>
        <u-form-item :label-width="labelWidth" label="寄件人" prop="orgUuid" label-position="left" >
          <u-input
              placeholder=""
              :disabled="true"
              :custom-style="pointerStyle"
              v-model="formData.sender"
          >
          </u-input>
        </u-form-item>
        <u-form-item :label-width="labelWidth" label="寄件人手机号码" prop="orgUuid" label-position="left" >
          <u-input
              placeholder=""
              :disabled="true"
              :custom-style="pointerStyle"
              v-model="formData.senderTel"
          >
          </u-input>
        </u-form-item>
        <u-form-item :label-width="labelWidth" label="收件人" prop="orgUuid" label-position="left" >
          <u-input
              placeholder=""
              :disabled="true"
              :custom-style="pointerStyle"
              v-model="formData.receiver"
          >
          </u-input>
        </u-form-item>
        <u-form-item :label-width="labelWidth" label="收件人手机号码" prop="orgUuid" label-position="left" >
          <u-input
              placeholder=""
              :disabled="true"
              :custom-style="pointerStyle"
              v-model="formData.receiverTel"
          >
          </u-input>
        </u-form-item>

      </u-form>
      <view class="submit-btns" style="margin-bottom: 60rpx">
        <u-button style="float: left" plain class="u-btn" type="primary" @click="myRetail">
          查看周边零售户(500米)
        </u-button>
        <u-button style="float: left" class="u-btn" type="primary" @click="myInfo">
          面单详情
        </u-button>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { AMapMixin, } from '@/common/AMapMixin.js';
import intelligenceservice from "@/service/intelligence/intelligence.service";
import { SET_MAP_LAT_LON, } from '@/config/setting.config.js';
import USearch from '@/uview-ui/components/u-search/u-search.vue';
import UIcon from '@/uview-ui/components/u-icon/u-icon.vue';
import mapLevelA from '@/static/map/mapLevelAnew.png';
import mapLevelB from '@/static/map/mapLevelBnew.png';
import mapLevelASel from '@/static/map/mapLevelAnewSel.png';
import mapLevelBSel from '@/static/map/mapLevelBnewSel.png';
import iconBlue from '@/static/map/map_icon_blue.png';
import SelectPartyComponent from "@/pages/case/components/selectPartyComponent.vue";
import DicInput from "@/components/dic_input.vue";
import AutoInput from "@/components/autoInput.vue";
import mUpload from "@/components/m-upload.vue";
export default {
  components: {
    mUpload, AutoInput, DicInput,
    SelectPartyComponent,
    UIcon,
    USearch,
  },
  mixins: [AMapMixin, ],
  data() {
    return {
      markers: [],
      currPosition: undefined,
      archiveList: [],
      northeastLatitude: '',
      northeastLongitude: '',
      southwestLatitude: '',
      southwestLongitude: '',
      cluster: undefined,
      searchPlac: '',
      judgmentId: '',
      title: '面单地图',
      longitude: '',
      latitude: '',
      orgUuid: '',
      positionPicker: undefined,
      selRetailerList: [],
      iconMap:{
        mapLevelA,
        mapLevelB,
        mapLevelASel,
        mapLevelBSel,
        iconBlue
      },
      partySelectShow: false,
      formData: {},
      pointerStyle: {
        marginRight: "5px",
        pointerEvents: "none !important"
      },
      labelWidth: '240',
      retailerType: 1
    };
  },
  onLoad(opt) {
    this.showDefaultTitle = false;
    this.judgmentId = opt.id;
    this.judgmentInit(opt);
    let self = this;
    if (this.$deviceApi.geolocation) {
      this.$deviceApi.geolocation().then((res) => {
        self.longitude = res.longitude;
        self.latitude = res.latitude;
      });
    } else {
      self.longitude = SET_MAP_LAT_LON[0];
      self.latitude = SET_MAP_LAT_LON[1];
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.$modal.showLoading('地图加载中...');
    },
    judgmentInit(opt) {
      this.updateMixinTitle(this.title);
    },
    initAmap() {
      let self = this;
      // #ifdef H5-DINGDING || H5-WECHAT || H5-EMP
      this.$deviceApi.geolocation().then(
          (res) => {
            self.curPos = [res.longitude, res.latitude];
            self.setMapInstance([res.longitude, res.latitude]);
          },
          (err) => {
            self.curPos = SET_MAP_LAT_LON;
            self.setMapInstance(SET_MAP_LAT_LON);
          }
      );
      // #endif
      // #ifdef H5-ONLY
      this.getCurrentLocation().then(
          (res) => {
            self.curPos = [res.lng, res.lat, ];
            self.setMapInstance([res.lng, res.lat, ]);
          },
          (err) => {
            self.curPos = SET_MAP_LAT_LON;
            self.setMapInstance(SET_MAP_LAT_LON);
          }
      );
      // #endif
    },
    setMapInstance(cords) {
      if (!this.hasInited) return;
      let self = this;
      self.curCords = new AMap.LngLat(cords[0], cords[1]);
      self.amap = new AMap.Map('container', {
        center: self.curCords,
        showControlButton: true,
        zoom: 18,
      });
      // self.amap.setZooms([13, 30,]);
      self.setCurrentPointMarker();
      this.$modal.hideLoading();
      self.loadPlugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.MapType', 'AMap.InfoWindow'], function() {
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        self.amap.addControl(new AMap.ToolBar());
        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
        self.amap.addControl(new AMap.Scale());
        // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
        let geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认:true
          timeout: 10000, // 超过10秒后停止定位，默认：5s
          // buttonPosition:'RB',    //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(5, 10), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          // zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
          content: '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>',
        });
        self.amap.addControl(geolocation);
      });
      // 地图缩放
      self.amap.on('zoomend', function() {
        self.getNearRetailer();
      });
      // 地图移动
      self.amap.on('moveend', function() {
        self.getNearRetailer();
      });
      self.getNearRetailer();
    },
    // 获取列表数据
    getNearRetailer() {
      let bounds = this.amap.getBounds();
      let params;
      let self = this;
      let information = '';
      let errInfo = '';
      params = {
        longitudeStart: bounds.southwest.lng, // 西南
        latitudeStart: bounds.southwest.lat,
        longitudeEnd: bounds.northeast.lng,
        latitudeEnd: bounds.northeast.lat
      };
      information = '正在查询请稍等...';
      errInfo = '该区域没有面单信息！';
      if (this.amap.getZoom() < 2) {
        this.markers = [];
        if (this.cluster) {
          this.amap.remove(this.cluster);
        }
        if (this.$storage.get('showMapZoomTip') != '1') {
          this.$modal.alert(
              '地图层级收缩，不支持查询，查询数据请将地图层级扩大。',
              '提示',
              () => {
                this.$storage.set('showMapZoomTip', '1');
              },
              '不再提示'
          );
        }
        return;
      }
      this.$modal.showLoading(information);
      this.markers = [];
      intelligenceservice.findBillMapList(params)
          .then((res) => {
            this.$modal.hideLoading();
            if (res.success) {
              self.archiveList = res.data;
              if (res.data.length != 0) {
                res.data.forEach((retailer, index) => {
                  if (retailer.receiverGisX && retailer.receiverGisY) {
                    this.addMarker(retailer, res.data, 1);
                  }
                  if (retailer.senderGisX && retailer.senderGisY) {
                    this.addMarker(retailer, res.data, 2);
                  }
                });
                this.markerCluster();
              } else {
                this.$u.toast(errInfo);
              }
            } else {
              this.$modal.hideLoading();
              self.$u.toast(res.msg);
            }
          })
          .catch((error) => {
            self.$u.toast(error);
          });
    },
    // 在地图上添加点
    addMarker(retailer, retailerData, selected) {
      let self = this;
      if (retailer.markerA) { this.map.remove(retailer.markerA); }
      if (retailer.markerB) { this.map.remove(retailer.markerB); }
      if (retailer.receiverGisX && retailer.receiverGisY) {
        let markerConfigA;
        // 零售户年检查次数未检查
        let ifSel = selected ? 'Sel' : '';
        let iconA = this.iconMap['mapLevelA' + ifSel];
        markerConfigA = {
          // icon,
          title: retailer.receiver,
          position: [retailer.receiverGisX, retailer.receiverGisY,],
          offset: new AMap.Pixel(-14, -20),
          content: `<div><img class="retailer-icon-show" style="width: 40px;height: 40px" src="${iconA}" /><span style="position: absolute;top: -6px;left: 12px">收</span></div>`,
        };
        // task.markerA = marker;
        let markerA = new AMap.Marker(markerConfigA);
        markerA.on('click', (e) => {
          this.retailerType = 1;
          this.partySelectShow = true;
          this.formData = retailer;
          // this.showInfoWindow(retailer, 1);
          // this.clickAddToList(retailer);
          // 添加零售户
          // this.addMarkerRetail(retailer, 1)
          // this.addMarkerRetail()
        });
        markerA.setMap(this.amap); // 在地图上添加点
        this.markers.push(markerA);
      }
      if (retailer.senderGisX && retailer.senderGisY) {
        let markerConfigB;
        // 零售户年检查次数未检查
        let ifSel = selected ? 'Sel' : '';
        let iconB = this.iconMap['mapLevelB' + ifSel];
        markerConfigB = {
          title: retailer.receiver,
          position: [retailer.senderGisX, retailer.senderGisY,],
          offset: new AMap.Pixel(-14, -20),
          content: `<div><img class="retailer-icon-show" style="width: 40px;height: 40px" src="${iconB}" /><span style="position: absolute;top: -6px;left: 12px">收</span></div>`,
        };
        let markerB = new AMap.Marker(markerConfigB);
        markerB.on('click', () => {
          this.retailerType = 2;
          this.partySelectShow = true;
          this.formData = retailer;
          // this.showInfoWindow(retailer, 2);
          // this.clickAddToList(retailer);
          // 添加零售户
          // this.addMarkerRetail(retailer, 2)
          // this.addMarkerRetail()
        });
        markerB.setMap(this.amap); // 在地图上添加点
        this.markers.push(markerB);
      }
    },
    // 周边零售户
    myRetail() {
      this.addMarkerRetail()
    },
    // 详情
    myInfo() {
      let complaint = {
        type: 'view',
        caseCode: this.formData.caseCode,
        caseUuid: this.formData.caseUuid,
      };
      if(this.formData){
        complaint.param = this.formData;
      }
      this.setRouteParam(complaint);
      this.$u.route('pages/case/caseInfoTemp/faceOrderInfo');
    },
    // 查看详情
    showInfoWindow(retailer, type) {
      let html = `
          <div class="info-window">
            <h3 class="title">
              ${retailer.billCode || ''}
            </h3>
            <div class="content">
              <div>快递公司名称：${retailer.expressName || '/'}</div>
              <div>包裹数量：${retailer.packageNum || '/'}</div>
              <div>寄件人：${retailer.sender || '/'}</div>
              <div>收件人：${retailer.receiver || '/'}</div>
              <a
                href="javascript:void(0)"
                class="detail"
                uuid="${retailer.uuid}"
                caseUuid="${retailer.caseUuid}"
                retailer="${retailer}"
                bizType="detailShow"
                id="detailShow"
              >详细信息</a>
            </div>
          </div>
    `;
      let infoWindow = new AMap.InfoWindow({
        content: html,
        offset: new AMap.Pixel(0, -20),
        autoMove: false,
      });
      if (type === 1) {
        infoWindow.open(this.amap, [retailer.receiverGisX, retailer.receiverGisY,]);
      } else {
        infoWindow.open(this.amap, [retailer.senderGisX, retailer.senderGisY,]);
      }
      // AMap.event.trigger(infoWindow, 'click', () => {
      //   console.log('infoWindow', infoWindow)
      // });
    },

    clickAddToList(task) {
      let ifSel = false;
      this.selRetailerList.map((item) => {
        if (item.uuid === task.uuid) {
          ifSel = true;
        }
      });
      if (!ifSel) {
        this.selRetailerList.push(task);
        this.addMarker(task, true);
      }
    },

    addMarkerRetail() {
      let formData = this.formData;
      let params = {
        distance: 500
      }
      // 108.495400,22.786090
      if (Number(this.retailerType) === 1) {
        params.longitude = formData.receiverGisX;
        params.latitude = formData.receiverGisY;
      } else {
        params.longitude = formData.senderGisX;
        params.latitude = formData.senderGisY;
      }
      intelligenceservice.queryLicPositionInfo(params).then(res => {
        res.data?.forEach(ele => {
          // 108.495245,22.786930
          this.addMapMarker(ele)
        })
        // this.addMapMarker({
        //   longitude: 108.495245,
        //   latitude: 22.786930,
        //   companyName: '测试用'
        // })
      })
      // clueService.queryLicPositionInfo(params).then(res => {
      //   res.data.forEach(ele => {
      //     this.addMapMarker(ele)
      //   })
      // })
    },

    addMapMarker(retailer) {
      let markPoint;
      let iconBlue = this.iconMap['iconBlue'];
      if (retailer.longitude && retailer.latitude) {
        markPoint = {
          title: retailer.companyName, // 显示的零售户名称
          position: [retailer.longitude, retailer.latitude],
          offset: new AMap.Pixel(-14, -20),
          content: `<div style="width: 200px"><img style="20px;height: 20px" class="retailer-icon-show" src="${iconBlue}" /><span style="position: absolute;top: -10px;left: 0px">${retailer.companyName}</span></div>`,
        };
        let marker = new AMap.Marker(markPoint);
        this.markers.push(marker)
        this.amap.add(marker)
      }
    },


    // 点聚合方法
    markerCluster() {
      let self = this;
      let count = this.markers.length;
      let renderClusterMarkers = function(context) {
        let factor = Math.pow(context.count / count, 1 / 18);
        let div = document.createElement('div');
        let Hue = 180 - factor * 180;
        let bgColor = 'hsla(' + Hue + ',100%,50%,0.7)';
        let fontColor = 'hsla(' + Hue + ',100%,20%,1)';
        let borderColor = 'hsla(' + Hue + ',100%,40%,1)';
        let shadowColor = 'hsla(' + Hue + ',100%,50%,1)';
        div.style.backgroundColor = bgColor;
        let size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
        div.style.width = div.style.height = size + 'px';
        div.style.border = 'solid 1px ' + borderColor;
        div.style.borderRadius = size / 2 + 'px';
        div.style.boxShadow = '0 0 1px ' + shadowColor;
        div.innerHTML = context.count;
        div.style.lineHeight = size + 'px';
        div.style.color = fontColor;
        div.style.fontSize = '14px';
        div.style.textAlign = 'center';
        context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
        context.marker.setContent(div);
      };
      this.amap.plugin(['AMap.MarkerClusterer', ], function() {
        if (self.cluster) {
          self.cluster.setMap(null);
        }
        self.cluster = new AMap.MarkerClusterer(
            self.amap, // 地图实例
            self.markers, // 海量点组成的数组
            {
              gridSize: 80,
              renderClusterMarker: renderClusterMarkers,
            }
        );
      });
    },
    toCurrent() {
      let self = this;
      this.getCurrentLocation().then(
          (res) => {
            self.curCords = new AMap.LngLat(res.lng, res.lat);
            self.curPos = [res.lng, res.lat, ];
            self.updateCurrentPointMarker();
          },
          (err) => {
            self.updateCurrentPointMarker();
          }
      );
    },
    // 确定按钮 跳转到零售户列表页面
    gotoSearch() {
      switch (Number(this.judgmentId)) {
        case 0:
          this.$u.route('pages/retailer/retailerList/retailerList');
          break;
        case 1:
          this.$u.route('pages/query/nolicence/nolicence');
          break;
        case 2:
          this.$u.route('pages/query/specialArea/specialAreaList');
          break;

        default:
          break;
      }
    },
    getContainerHeight() {
      let p = this.$u.sys().windowHeight - 44 - this.$u.sys().statusBarHeight + 'px'
      // #ifdef H5-WECHAT
      p = this.$u.sys().windowHeight - this.$u.sys().statusBarHeight + 'px'
      // #endif
      return p;
    },
    getContainerWidth() {
      return this.$u.sys().windowWidth + 'px';
    },
    justInitMap() {
      this.$modal.alert('请在设备的设置中开启APP的定位权限后重新获取当前位置');
      this.amap = new AMap.Map('container', {
        showControlButton: true,
        zoom: 18,
      });
      this.$modal.hideLoading();
    },
    /**
     * 从扫描或NFC获取的零售户信息中提取许可证号
     * 不同的地区二维码信息不同，如果无法识别，需要修改本方法，添加相关特列
     * 通用逻辑：查找到“许可证”后的第一个数字串即认为是许可证号
     */
    getLicenseCode(scanRetailerInfo) {
      let index = scanRetailerInfo.indexOf('许可证号:');
      let qCodeStr = '';
      let lic = '';
      if (index != -1) qCodeStr = scanRetailerInfo.substring(index, scanRetailerInfo.indexOf(','));
      !qCodeStr && (qCodeStr = scanRetailerInfo.substring(0, 12));
      if (!qCodeStr) {
        lic = '';
      }
      let matches = qCodeStr.match(/[0-9]+/);
      if (matches.length > 0) lic = matches[0]; // 识别成功
      if (!this.$u.test.isEmpty(lic)) {
        try {
          lic = this.$u.trim(lic);
        } catch (e) {
          console.log(e);
        }
      }
      return lic;
    },
    // nfc按钮
    onNFC() {
      // #ifdef H5-DINGDING
      this.$deviceApi.nfcReader && this.$deviceApi.nfcReader().then((code) => {
        if (!code) {
          this.$u.toast('无法识别');
          return;
        }
        let nfcNo = '';
        if (code['tagId']) {
          nfcNo = code['tagId'].replace(/:/g, '');
        } else {
          nfcNo = code.replace(/:/g, '');
        }
        this.getRetailerByCode(nfcNo);
      }).catch((error) => {
        this.$u.toast(error);
      })
      // #endif
      // #ifndef H5-DINGDING
      this.$u.toast('H5不支持NFC');
      // #endif
    },
    getRetailerByCode(code) {
      certificateService
          .getRetailerListByLicenseCodes({
            licNoStr: code,
          })
          .then((rt) => {
            if (rt.success && rt.data.length > 0) {
              this.gotoDetail(rt.data[0]);
            } else {
              this.$u.toast(rt.msg);
            }
          })
          .catch((error) => {
            this.$u.toast(error);
          });
    },
    // 查看零售户详情
    gotoDetail(retailer) {
      this.$u.route('pages/retailer/retailerInfo/retailerInfo', {
        retailerUuid: retailer.retailerUuid,
      });
    },
    // 返回按钮
    retailBack() {
      this.$deviceApi.nfcStop && this.$deviceApi.nfcStop();
      let self = this;
      self.backPrev({
        paramKey: 'data',
        param: {},
      });
    },
  },
};
</script>

<style scoped lang="scss">
.page {
  padding: 0;
}

@import '../../../style/certificate/common.scss';

.nolicence-search-lay {
  position: fixed;
  // #ifndef H5-DINGDING
  top: 44px;
  // #endif
  // #ifdef H5-DINGDING
  top: 0px;
  // #endif
  z-index: 99;
  width: 100%;
  padding: $cm-search-padding-row 0;
}

.search-right-icon {
  display: flex;
  position: absolute;
  right: 8%;
}

uni-page-body {
  min-height: 100%;
  width: 100%;
  background-color: #f1f0f6;
}

#container {
  width: 100%;
  height: calc(100% - 88px);
}

.u-search-title {
  background: #fff;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 44px;
}

.u-search-btn {
  height: 44px;
  line-height: 44px;
  // padding: 0 10px;
  display: flex;
  align-items: center;
  margin: 0 20rpx;

  .u-confirm-btn {
    height: 32px;
    margin-left: 10px;
  }
}

// 搜索框内容
.u-serach-info {
  background-color: #f4f4f5;
  position: fixed;
  /* #ifdef H5-DINGDING  */
  top: 0px;
  /* #endif */
  /* #ifndef H5-DINGDING  */
  top: calc(var(--status-bar-height) + 44px);
  /* #endif */
  z-index: 1;
  width: 100%;
  padding-right: 11px;
}

.u-l-item {
  margin-top: 88px;
}

.cur-loc {
  position: absolute;
  bottom: 30px;
  left: 10px;
  padding: 5px;
  background: #fff;
  width: 35px;
  height: 35px;
  box-shadow: 0px 0px 0px 1px #ddd;
}
</style>
